<?php

namespace app\shop\service;

use app\common\model\plus\agent\Setting as AgentSetting;
use app\common\service\product\BaseProductService;
use app\shop\model\product\BrandModel;
use app\shop\model\product\Category as CategoryModel;
use app\shop\model\settings\Delivery as DeliveryModel;
use app\shop\model\user\Grade as GradeModel;
use app\shop\model\product\ProductBrandRelationModel;

/**
 * 商品服务类
 */
class ProductService extends BaseProductService
{
    /**
     * 商品管理公共数据
     */
    public static function getEditData($model = null, $scene = 'edit')
    {
        // 商品分类
        $category = CategoryModel::getCacheTree();

        //kevin 2024/5/16 根据文档需求将选择二级分类的时候一级分类也要显示出来
        $new_category = $category;
        foreach ($new_category as $key => $value){
            if($value['parent_id']==0){
                $new_category[$key]['category_name_text'] = $value['name'];
            }
            if(isset($value['child'])){
                foreach ($value['child'] as $k => $v){
                    if($v['parent_id'] == $value['category_id']){
                        $value['child'][$k]['category_name_text'] = $value['name'].'-'.$v['name'];
                        $new_category[$key]['child'] = $value['child'];
                    }
                }
            }
        }

        // 商品品牌
        $brand = BrandModel::listAll();
        $selectBrand = ProductBrandRelationModel::listAll(['product_id' => $model['product_id']], ['brand']);
        foreach ($selectBrand as &$item) {
            $item['name'] = $item['brand']['name'];
        }
        // 配送模板,仅仅查当前模板
        $delivery = [];
        if ($model) {
            $delivery = [DeliveryModel::detail($model['delivery_id'])];
        }
        // 会员等级列表
        $gradeList = GradeModel::getUsableList();
        // 商品sku数据
        $specData = static::getSpecData($model);
        // 商品规格是否锁定
        $isSpecLocked = static::checkSpecLocked($model, $scene);
        // 平台分销规则
        $agentSetting = AgentSetting::getItem('commission');
        $basicSetting = AgentSetting::getItem('basic');
        return compact('category', 'new_category','brand', 'selectBrand', 'delivery', 'gradeList', 'specData', 'isSpecLocked', 'agentSetting', 'basicSetting');
    }
}
